<script setup lang="ts">
import { reactive } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import type { PageParams } from "@/types/home";
import useHomeStore from "@/pinia/modules/homeStore";
import useCartStore from "@/pinia/modules/cartStore";
import useUserStore from "@/pinia/modules/userStore";
import Guess from "@/components/guess.vue";
import type { CartItem } from "@/types/cart";

const homeStore = useHomeStore();

const cartStore = useCartStore();

const userStore = useUserStore();

const { guessList, guessListTotal } = storeToRefs(homeStore);

const { userInfo } = storeToRefs(userStore);

const { cartList, selectedAll, totalCount, total } = storeToRefs(cartStore);

/*获取猜你喜欢列表的分页参数*/
const pageParams = reactive<PageParams>({
    page: 1,
    pageSize: 10,
});

/*获取猜你喜欢的请求函数*/
const fetchGuess = async () => {
    try {
        await homeStore.fetchGuess(pageParams);
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*获取购物车列表的函数*/
const fetchCartList = async () => {
    if (!userInfo.value.id) return;
    try {
        cartStore.fetchCartList();
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*删除购物车商品的函数*/
const deleteCart = (skuId: string) => {
    uni.showModal({
        title: "提示",
        content: "确认删除该商品吗?",
        success: async function(result) {
            if (result.confirm) {
                try {
                    await cartStore.deleteCart({ ids: [skuId] });
                    await fetchCartList();
                    uni.showToast({ title: "删除成功", icon: "error", duration: 2000 });
                } catch (error: any) {
                    await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
                }
            } else if (result.cancel) {
                console.log("用户点击取消");
            }
        },
    });
};

/*修改商品数量的函数*/
const changeCount = async (cart: CartItem, step: number) => {
    try {
        const count: number = cart.count += step;
        cart.count = count;
        await cartStore.changeCart({ count }, cart.skuId);
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }

};

/*修改商品选中状态的函数*/
const changeSelected = async (cart: CartItem) => {
    try {
        const selected: boolean = !cart.selected;
        cart.selected = selected;
        await cartStore.changeCart({ selected }, cart.skuId);
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*全选和取消全选的函数*/
const changeSelectedAll = async () => {
    try {
        const selected = !selectedAll.value;
        await cartStore.changeSelectedAll({ selected });
        await fetchCartList();
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*结算按钮的回调函数*/
const handlePayment = () => {
    if (totalCount.value === 0) return uni.showToast({ title: "请选择商品", icon: "error", duration: 2000 });
    uni.navigateTo({
        url:"/subPackages/order/order"
    })

};

onReachBottom(() => {
    if (guessList.value.length >= guessListTotal.value) return uni.showToast({ title: "商品加载完毕", icon: "error", duration: 2000 });
    fetchGuess();
});


onLoad(() => {
    fetchGuess();
});

onShow(() => {
    fetchCartList();
});
</script>

<template>
    <scroll-view scroll-y class="scroll-view">
        <!-- 已登录: 显示购物车 -->
        <template v-if="userInfo.id">
            <!-- 购物车列表 -->
            <view class="cart-list" v-if="cartList.length">
                <!-- 优惠提示 -->
                <view class="tips">
                    <text class="label">满减</text>
                    <text class="desc">满1件, 即可享受9折优惠</text>
                </view>
                <!-- 滑动操作分区 -->
                <uni-swipe-action>
                    <!-- 滑动操作项 -->
                    <uni-swipe-action-item v-for="(item) in cartList" :key="item.skuId" class="cart-swipe">
                        <!-- 商品信息 -->
                        <view class="goods">
                            <!-- 选中状态 -->
                            <text class="checkbox" :class="{ checked: item.selected }" @click="changeSelected(item)"></text>
                            <navigator :url="`/subPackages/detail/detail?id=${item.id}`" hover-class="none" class="navigator">
                                <image mode="aspectFill" class="picture" :src="item.picture"></image>
                                <view class="meta">
                                    <view class="name ellipsis">{{ item.name }}</view>
                                    <view class="attrsText ellipsis">{{ item.attrsText }}</view>
                                    <view class="price">{{ item.nowPrice }}</view>
                                </view>
                            </navigator>
                            <!-- 商品数量 -->
                            <view class="count">
                                <text class="text" @click="changeCount(item,-1)">-</text>
                                <input class="input" type="number" :value="item.count" />
                                <text class="text" @click="changeCount(item,+1)">+</text>
                            </view>
                        </view>
                        <!-- 右侧删除按钮 -->
                        <template #right>
                            <view class="cart-swipe-right">
                                <button class="button delete-button" @click="deleteCart(item.skuId)">删除</button>
                            </view>
                        </template>
                    </uni-swipe-action-item>
                </uni-swipe-action>
            </view>
            <!-- 购物车空状态 -->
            <view class="cart-blank" v-else>
                <image src="/static/images/blank_cart.png" class="image" />
                <text class="text">购物车还是空的，快来挑选好货吧</text>
                <navigator open-type="switchTab" url="/pages/home/home" hover-class="none">
                    <button class="button">去首页看看</button>
                </navigator>
            </view>
            <!-- 吸底工具栏 -->
            <view class="toolbar">
                <text class="all" :class="{ checked: selectedAll&cartList.length!==0 }" @click="changeSelectedAll">全选</text>
                <text class="text">合计:</text>
                <text class="amount">{{ total.toFixed(2) }}</text>
                <view class="button-grounp">
                    <view class="button payment-button" @click="handlePayment"> 结算({{ totalCount }})</view>
                </view>
            </view>
        </template>
        <!-- 未登录: 提示登录 -->
        <view class="login-blank" v-else>
            <text class="text">登录后可查看购物车中的商品</text>
            <navigator url="/pages/login/login" hover-class="none">
                <button class="button">去登录</button>
            </navigator>
        </view>
        <!-- 猜你喜欢 -->
        <guess title="猜你喜欢" :guess-list="guessList"></guess>
        <!-- 底部占位空盒子 -->
        <view class="toolbar-height"></view>
    </scroll-view>
</template>

<style lang="scss">
page {
    background-color: #f4f4f4;
}

:host {
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background-color: #f7f7f8;
}


.scroll-view {
    flex: 1;
}


.cart-list {
    padding: 0 20rpx;

    .tips {
        display: flex;
        align-items: center;
        line-height: 1;
        margin: 30rpx 10rpx;
        font-size: 26rpx;
        color: #666;

        .label {
            color: #fff;
            padding: 7rpx 15rpx 5rpx;
            border-radius: 4rpx;
            font-size: 24rpx;
            background-color: #27ba9b;
            margin-right: 10rpx;
        }
    }


    .goods {
        display: flex;
        padding: 30rpx 30rpx 30rpx 80rpx;
        border-radius: 10rpx;
        background-color: #fff;
        position: relative;

        .navigator {
            display: flex;
        }

        .checkbox {
            position: absolute;
            top: 0;
            left: 0;

            display: flex;
            align-items: center;
            justify-content: center;
            width: 80rpx;
            height: 100%;

            &::before {
                content: '\e6cd';
                font-family: 'erabbit' !important;
                font-size: 40rpx;
                color: #444;
            }

            &.checked::before {
                content: '\e6cc';
                color: #27ba9b;
            }
        }

        .picture {
            width: 170rpx;
            height: 170rpx;
        }

        .meta {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 20rpx;
        }

        .name {
            height: 72rpx;
            font-size: 26rpx;
            color: #444;
        }

        .attrsText {
            line-height: 1.8;
            padding: 0 15rpx;
            font-size: 24rpx;
            align-self: flex-start;
            border-radius: 4rpx;
            color: #888;
            background-color: #f7f7f8;
        }

        .price {
            line-height: 1;
            font-size: 26rpx;
            color: #444;
            margin-bottom: 2rpx;
            color: #cf4444;

            &::before {
                content: '￥';
                font-size: 80%;
            }
        }


        .count {
            position: absolute;
            bottom: 20rpx;
            right: 5rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 220rpx;
            height: 48rpx;

            .text {
                height: 100%;
                padding: 0 20rpx;
                font-size: 32rpx;
                color: #444;
                background-color: #f6f6f6;
            }

            .input {
                height: 100%;
                text-align: center;
                border-radius: 4rpx;
                font-size: 24rpx;
                color: #444;
                background-color: #f6f6f6;
                margin: 0 10rpx;
            }
        }
    }

    .cart-swipe {
        display: block;
        margin: 20rpx 0;
    }

    .cart-swipe-right {
        display: flex;
        height: 100%;

        .button {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 50px;
            padding: 6px;
            line-height: 1.5;
            color: #fff;
            font-size: 26rpx;
            border-radius: 0;
        }

        .delete-button {
            background-color: #cf4444;
        }
    }
}


.cart-blank,
.login-blank {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 60vh;

    .image {
        width: 400rpx;
        height: 281rpx;
    }

    .text {
        color: #444;
        font-size: 26rpx;
        margin: 20rpx 0;
    }

    .button {
        width: 240rpx !important;
        height: 60rpx;
        line-height: 60rpx;
        margin-top: 20rpx;
        font-size: 26rpx;
        border-radius: 60rpx;
        color: #fff;
        background-color: #27ba9b;
    }
}


.toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: var(--window-bottom);
    z-index: 1;

    height: 100rpx;
    padding: 0 20rpx;
    display: flex;
    align-items: center;
    border-top: 1rpx solid #ededed;
    border-bottom: 1rpx solid #ededed;
    background-color: #fff;
    box-sizing: content-box;

    .all {
        margin-left: 25rpx;
        font-size: 14px;
        color: #444;
        display: flex;
        align-items: center;
    }

    .all::before {
        font-family: 'erabbit' !important;
        content: '\e6cd';
        font-size: 40rpx;
        margin-right: 8rpx;
    }

    .checked::before {
        content: '\e6cc';
        color: #27ba9b;
    }

    .text {
        margin-right: 8rpx;
        margin-left: 32rpx;
        color: #444;
        font-size: 14px;
    }

    .amount {
        font-size: 20px;
        color: #cf4444;

        .decimal {
            font-size: 12px;
        }

        &::before {
            content: '￥';
            font-size: 12px;
        }
    }

    .button-grounp {
        margin-left: auto;
        display: flex;
        justify-content: space-between;
        text-align: center;
        line-height: 72rpx;
        font-size: 13px;
        color: #fff;

        .button {
            width: 240rpx;
            margin: 0 10rpx;
            border-radius: 72rpx;
        }

        .payment-button {
            background-color: #27ba9b;

            &.disabled {
                opacity: 0.6;
            }
        }
    }
}

.toolbar-height {
    height: 100rpx;
}
</style>
